<!--收款单-->
<template>
  <div class="receipt-container">
    <!-- 筛选区域 -->
    <div class="controls-section">
      <div class="filters">
        <button class="btn-primary" @click="openCreateModal">新建</button>
        <div class="filter-item">
          <label>收款单号</label>
          <input type="text" v-model="searchForm.receiptOrderNo" placeholder="请输入收款单号">
        </div>
        <div class="filter-item">
          <label>收款状态</label>
          <select v-model="searchForm.receiptStatus">
            <option value="">全部</option>
            <option value="0">待核销</option>
            <option value="1">部分核销</option>
            <option value="2">全部核销</option>
          </select>
        </div>
      </div>
      <div class="actions">
        <button class="btn-primary" @click="search">搜索</button>
        <button class="btn-secondary" @click="resetSearch">重置</button>
      </div>
    </div>

    <!-- 表格区域 -->
    <div class="table-section">
      <table>
        <thead>
          <tr>
            <th>收款单号</th>
            <th>收款状态</th>
            <th>客户</th>
            <th>关联销售单</th>
            <th>应收总额</th>
            <th>已核销金额</th>
            <th>待核销金额</th>
            <th>财务人员</th>
            <th>创建日期</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="item in receiptList" :key="item.id">
            <td class="link-style" @click="viewDetail(item)">{{ item.receiptOrderNo }}</td>
            <td><span :class="statusClass(item.receiptStatus)">{{ getStatusText(item.receiptStatus) }}</span></td>
            <td>{{ item.customerName || `客户${item.customerId}` }}</td>
            <td>{{ item.relatedSalesOrder }}</td>
            <td>{{ formatMoney(item.receivableAmount) }}</td>
            <td>{{ formatMoney(item.writtenOffAmount) }}</td>
            <td>{{ formatMoney(item.toBeWrittenOff) }}</td>
            <td>{{ item.financeUserName || item.uId || '-' }}</td>
            <td>{{ formatDate(item.creationDate) }}</td>
          </tr>
        </tbody>
      </table>
    </div>

    <!-- 分页区域 -->
    <div class="pagination-section">
      <div class="pagination-info">
        共 {{ pagination.total }} 条记录
      </div>
      <div class="pagination-controls">
        <button
          :disabled="pagination.current <= 1"
          @click="changePage(pagination.current - 1)"
          class="pagination-btn"
        >
          ‹
        </button>
        <button class="pagination-btn active" disabled>{{ pagination.current }}</button>
        <button
          :disabled="pagination.current >= totalPages"
          @click="changePage(pagination.current + 1)"
          class="pagination-btn"
        >
          ›
        </button>
        <select v-model.number="pagination.size" @change="changePageSize" class="page-size-select">
          <option value="5">5条/页</option>
          <option value="10">10条/页</option>
          <option value="20">20条/页</option>
        </select>
      </div>
    </div>

    <!-- 详情抽屉 -->
    <div class="detail-drawer" :class="{ 'show': showDetailDrawer }">
      <div class="drawer-header">
        <h3>收款单详情</h3>
        <button class="close-btn" @click="closeDetailDrawer">×</button>
      </div>
      <div class="drawer-content" v-if="currentReceipt">
        <div class="detail-section">
          <h4>基本信息</h4>
          <div class="detail-grid">
            <div class="detail-item">
              <label>收款单号：</label>
              <span>{{ currentReceipt.receiptOrderNo }}</span>
            </div>
            <div class="detail-item">
              <label>收款状态：</label>
              <span :class="statusClass(currentReceipt.receiptStatus)">{{ getStatusText(currentReceipt.receiptStatus) }}</span>
            </div>
            <div class="detail-item">
              <label>客户：</label>
              <span>{{ currentReceipt.customerName || `客户${currentReceipt.customerId}` }}</span>
            </div>
            <div class="detail-item">
              <label>关联销售单：</label>
              <span>{{ currentReceipt.relatedSalesOrder }}</span>
            </div>
          </div>
        </div>

        <div class="detail-section">
          <h4>金额信息</h4>
          <div class="detail-grid">
            <div class="detail-item">
              <label>应收总额：</label>
              <span class="amount">{{ formatMoney(currentReceipt.receivableAmount) }}</span>
            </div>
            <div class="detail-item">
              <label>已核销金额：</label>
              <span class="amount">{{ formatMoney(currentReceipt.writtenOffAmount) }}</span>
            </div>
            <div class="detail-item">
              <label>待核销金额：</label>
              <span class="amount">{{ formatMoney(currentReceipt.toBeWrittenOff) }}</span>
            </div>
          </div>
        </div>

        <div class="detail-section">
          <h4>其他信息</h4>
          <div class="detail-grid">
            <div class="detail-item">
              <label>财务人员：</label>
              <span>{{ currentReceipt.financeUserName || currentReceipt.uId || '-' }}</span>
            </div>
            <div class="detail-item">
              <label>创建日期：</label>
              <span>{{ formatDate(currentReceipt.creationDate) }}</span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 新建收款单模态框 -->
    <div class="modal-overlay" v-if="showCreateModal" @click="closeCreateModal">
      <div class="create-modal" @click.stop>
        <div class="modal-header">
          <h3>新建收款单</h3>
          <button class="close-btn" @click="closeCreateModal">×</button>
        </div>
        <div class="modal-content">
          <form @submit.prevent="submitCreate">
            <div class="form-grid">
              <div class="form-group">
                <label class="required">收款单号</label>
                <input type="text" v-model="createForm.receiptOrderNo" placeholder="请输入收款单号" maxlength="50" required>
              </div>

              <div class="form-group">
                <label class="required">客户ID</label>
                <input type="number" v-model="createForm.customerId" placeholder="请输入客户ID" required>
              </div>

              <div class="form-group">
                <label>关联销售单</label>
                <input type="text" v-model="createForm.relatedSalesOrder" placeholder="请输入关联销售单" maxlength="100">
              </div>

              <div class="form-group">
                <label class="required">应收总额</label>
                <input type="number" v-model="createForm.receivableAmount" placeholder="请输入应收总额" step="0.01" required>
              </div>

              <div class="form-group">
                <label class="required">已核销金额</label>
                <input type="number" v-model="createForm.writtenOffAmount" placeholder="请输入已核销金额" step="0.01" required>
              </div>

              <div class="form-group">
                <label>财务人员</label>
                <input type="number" v-model="createForm.uId" placeholder="请输入财务人员ID">
              </div>
            </div>

            <div class="form-actions">
              <button type="button" class="btn-secondary" @click="closeCreateModal">取消</button>
              <button type="submit" class="btn-primary" :disabled="submitting">
                {{ submitting ? '保存中...' : '保存' }}
              </button>
            </div>
          </form>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { receiptOrderPage, receiptOrderDetail, receiptOrderCreate } from '@/api/finance/receiptOrder'

export default {
  name: 'Receipt',
  data() {
    return {
      // 搜索表单
      searchForm: {
        receiptOrderNo: '',
        customerId: '',
        relatedSalesOrder: '',
        receiptStatus: ''
      },

      // 分页信息
      pagination: {
        current: 1,
        size: 5,
        total: 0,
        pages: 0
      },

      // 收款单列表
      receiptList: [],

      // 详情抽屉
      showDetailDrawer: false,
      currentReceipt: null,

      // 新建模态框
      showCreateModal: false,
      submitting: false,
      createForm: {
        receiptOrderNo: '',
        customerId: '',
        relatedSalesOrder: '',
        receivableAmount: '',
        writtenOffAmount: '',
        uId: ''
      }
    }
  },

  computed: {
    totalPages() {
      const size = Number(this.pagination.size) || 10
      const total = Number(this.pagination.total) || 0
      return Math.max(1, Math.ceil(total / size))
    }
  },

  mounted() {
    this.loadData()
  },

  methods: {
    // 加载数据
    async loadData() {
      try {
        const params = {
          pageNum: this.pagination.current,
          pageSize: this.pagination.size,
          ...this.searchForm
        }

        // 处理空字符串
        Object.keys(params).forEach(key => {
          if (params[key] === '') {
            params[key] = null
          }
        })

        const { data } = await receiptOrderPage(params)
        const page = data?.data || data || {}
        this.receiptList = page.records || []
        // 同步总条数；current/size 以前端控件为准，避免被后端缺省值覆盖造成不可点击
        this.pagination.total = page.total || 0
      } catch (error) {
        console.error('加载数据失败:', error)
      }
    },

    // 搜索
    search() {
      this.pagination.current = 1
      this.loadData()
    },

    // 重置搜索
    resetSearch() {
      this.searchForm = {
        receiptOrderNo: '',
        customerId: '',
        relatedSalesOrder: '',
        receiptStatus: ''
      }
      this.pagination.current = 1
      this.loadData()
    },

    // 切换页码（边界保护）
    changePage(page) {
      if (page < 1 || page > this.totalPages) return
      this.pagination.current = page
      this.loadData()
    },

    // 切换每页条数
    changePageSize() {
      this.pagination.current = 1
      this.loadData()
    },

    // 查看详情
    async viewDetail(item) {
      if (!item || !item.id) return
      try {
        const { data } = await receiptOrderDetail(item.id)
        const detail = data?.data || data
        if (detail) {
          this.currentReceipt = detail
          this.showDetailDrawer = true
        }
      } catch (error) {
        console.error('获取详情失败:', error)
      }
    },

    // 关闭详情抽屉
    closeDetailDrawer() {
      this.showDetailDrawer = false
      this.currentReceipt = null
    },

    // 显示新建模态框
    openCreateModal() {
      this.showCreateModal = true
      this.resetCreateForm()
    },

    // 关闭新建模态框
    closeCreateModal() {
      this.showCreateModal = false
      this.resetCreateForm()
    },

    // 重置新建表单
    resetCreateForm() {
      this.createForm = {
        receiptOrderNo: '',
        customerId: '',
        relatedSalesOrder: '',
        receivableAmount: '',
        writtenOffAmount: '',
        uId: ''
      }
    },

    // 提交新建
    async submitCreate() {
      if (!this.createForm.receiptOrderNo || !this.createForm.customerId ||
          !this.createForm.receivableAmount || !this.createForm.writtenOffAmount) {
        alert('请填写必填字段')
        return
      }

      this.submitting = true
      try {
        const params = {
          ...this.createForm,
          customerId: Number(this.createForm.customerId),
          receivableAmount: Number(this.createForm.receivableAmount),
          writtenOffAmount: Number(this.createForm.writtenOffAmount),
          uId: this.createForm.uId ? Number(this.createForm.uId) : null
        }

        const response = await receiptOrderCreate(params)
        if (response.code === 200) {
          alert('创建成功')
          this.closeCreateModal()
          this.loadData()
        } else {
          alert(response.message || '创建失败')
        }
      } catch (error) {
        console.error('创建失败:', error)
        alert('创建失败')
      } finally {
        this.submitting = false
      }
    },

    // 状态样式
    statusClass(status) {
      if (status === 0) return 'status-pending'
      if (status === 1) return 'status-partial'
      if (status === 2) return 'status-verified'
      return ''
    },

    // 状态文本
    getStatusText(status) {
      if (status === 0) return '待核销'
      if (status === 1) return '部分核销'
      if (status === 2) return '全部核销'
      return '未知'
    },

    // 格式化金额
    formatMoney(amount) {
      if (amount == null) return '0.00'
      return Number(amount).toFixed(2)
    },

    // 格式化日期
    formatDate(date) {
      if (!date) return ''
      return new Date(date).toLocaleDateString()
      }
  }
}
</script>

<style scoped>
.receipt-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.title-section {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
}

.title-section h2 {
    font-size: 20px;
    font-weight: bold;
}

.controls-section {
  display: flex;
  justify-content: space-between;
  flex-wrap: wrap;
  gap: 16px;
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
  margin-bottom: 20px;
  align-items: center;
}

.filters {
    display: flex;
    flex-wrap: wrap;
    gap: 16px;
    align-items: center;
}

.filter-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.filter-item label {
  font-size: 14px;
  white-space: nowrap;
}

.filter-item input, .filter-item select {
  padding: 8px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  width: 150px;
}

.actions {
  display: flex;
  gap: 10px;
}

.btn-primary {
  background-color: #409eff;
  color: white;
  border: none;
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
}

.btn-secondary {
  background-color: #fff;
  color: #606266;
  border: 1px solid #dcdfe6;
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
}

.btn-link {
  background: none;
  border: none;
  color: #409eff;
  cursor: pointer;
  text-decoration: underline;
}

.table-section {
  background-color: #fff;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
}

table {
  width: 100%;
  border-collapse: collapse;
}

th, td {
  padding: 12px;
  text-align: left;
  border-bottom: 1px solid #ebeef5;
}

th {
  background-color: #f8f9fa;
  font-weight: 600;
}

.link-style {
    color: #409eff;
    cursor: pointer;
}

.link-style:hover {
    text-decoration: underline;
}

.status-pending {
    color: #f56c6c;
    background-color: #fef0f0;
    padding: 4px 8px;
    border-radius: 4px;
}

.status-partial {
    color: #e6a23c;
    background-color: #fdf6ec;
    padding: 4px 8px;
    border-radius: 4px;
}

.status-verified {
    color: #67c23a;
    background-color: #f0f9eb;
    padding: 4px 8px;
    border-radius: 4px;
}

/* 分页样式 */
.pagination-section {
  background-color: #fff;
  padding: 20px;
  border-radius: 8px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.pagination-info {
  color: #606266;
  font-size: 14px;
}

.pagination-controls {
  display: flex;
  align-items: center;
  gap: 8px;
}

.pagination-btn {
  padding: 6px 12px;
  border: 1px solid #dcdfe6;
  background-color: #fff;
  cursor: pointer;
  border-radius: 4px;
  min-width: 40px;
}

.pagination-btn:hover:not(:disabled) {
  border-color: #409eff;
  color: #409eff;
}

.pagination-btn.active {
  background-color: #409eff;
  color: white;
  border-color: #409eff;
}

.pagination-btn:disabled {
  cursor: not-allowed;
  opacity: 0.6;
}

.page-size-select {
  padding: 6px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
}

/* 详情抽屉样式 */
.detail-drawer {
  position: fixed;
  top: 0;
  right: -400px;
  width: 400px;
  height: 100vh;
  background-color: #fff;
  box-shadow: -2px 0 8px rgba(0, 0, 0, 0.1);
  transition: right 0.3s ease;
  z-index: 1000;
  overflow-y: auto;
}

.detail-drawer.show {
  right: 0;
}

.drawer-header {
  padding: 20px;
  border-bottom: 1px solid #ebeef5;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.drawer-header h3 {
  margin: 0;
  font-size: 18px;
}

.close-btn {
  background: none;
  border: none;
  font-size: 24px;
  cursor: pointer;
  color: #909399;
}

.close-btn:hover {
  color: #606266;
}

.drawer-content {
  padding: 20px;
}

.detail-section {
  margin-bottom: 24px;
}

.detail-section h4 {
  margin: 0 0 16px 0;
  font-size: 16px;
  color: #303133;
  border-bottom: 1px solid #ebeef5;
  padding-bottom: 8px;
}

.detail-grid {
  display: grid;
  gap: 12px;
}

.detail-item {
  display: flex;
  align-items: center;
}

.detail-item label {
  min-width: 100px;
  color: #606266;
  font-weight: 500;
}

.detail-item span {
  color: #303133;
}

.detail-item .amount {
  font-weight: 600;
  color: #409eff;
}

/* 新建模态框样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1001;
}

.create-modal {
  background-color: #fff;
  border-radius: 8px;
  width: 760px;
  max-height: 80vh;
  overflow-y: auto;
}

.modal-header {
  padding: 16px 20px;
  border-bottom: 1px solid #ebeef5;
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: #8ec7ff;
  color: #fff;
  border-radius: 8px 8px 0 0;
}

.modal-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
}

.modal-content {
  padding: 20px;
}

.form-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 16px 20px;
  margin-bottom: 24px;
}

.form-group {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.form-group label {
  font-weight: 500;
  color: #303133;
}

.form-group label.required::after {
  content: ' *';
  color: #f56c6c;
}

.form-group input {
  padding: 8px 12px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  font-size: 14px;
  height: 36px;
}

.form-group input:focus {
  outline: none;
  border-color: #409eff;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding-top: 20px;
  border-top: 1px solid #ebeef5;
}

/* Buttons in modal footer */
.form-actions .btn-secondary {
  height: 36px;
  padding: 0 16px;
}
.form-actions .btn-primary {
  height: 36px;
  padding: 0 16px;
}
</style>
